/*
 * #%L
 * SwiftUIBusinessLayer
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/**
 * 
 */
package com.linkwithweb.products.swiftui.plugins;

import java.util.ArrayList;
import java.util.Collection;

import org.java.plugin.registry.PluginDescriptor;
import org.springframework.web.context.support.XmlWebApplicationContext;

/**
 * @author ashwin kumar
 * 
 */
public class PluginWrapper extends org.java.plugin.Plugin {
	private final Collection<XmlWebApplicationContext> plugins = new ArrayList<XmlWebApplicationContext>();

	private final PluginDescriptor pluginDescriptor;
	private final PluginManager pluginManager;

	/**
	 * @param pluginManager
	 * @param pluginDescriptor
	 * @param plugin
	 */
	public PluginWrapper(PluginManager pluginManager, PluginDescriptor pluginDescriptor, Object plugin) {
		Class<?> clazz = plugin.getClass();

		this.pluginManager = pluginManager;
		this.pluginDescriptor = pluginDescriptor;

		processAnnotations(clazz);
	}

	/**
	 * @param clazz
	 */
	private void processAnnotations(Class<?> clazz) {
		Plugin plugin = clazz.getAnnotation(Plugin.class);

		XmlWebApplicationContext context = new XmlWebApplicationContext();

		context.setClassLoader(getPluginClassLoader());
		context.setNamespace(pluginDescriptor.getId());

		context.setConfigLocation(plugin.value());
		context.addBeanFactoryPostProcessor(new EventServiceBeanFactoryPostProcessor());

		plugins.add(context);
	}

	/**
	 * @return
	 */
	private ClassLoader getPluginClassLoader() {
		return pluginManager.getPluginClassLoader(pluginDescriptor);
	}

	@Override
	protected void doStart() throws Exception {
		for (XmlWebApplicationContext context : plugins) {
			pluginManager.registerApiPlugin(context);
		}
	}

	@Override
	protected void doStop() throws Exception {
	}
}